export default {
    name: "upload",
	props: {
		modelValue: {
			type: String,
			default: ''
		},
		action: {
			type: String,
			default: `${window.APP_CONFIG.baseurl}v1/upload`
		},
		data: {
			type: Object,
			default: () => ({name: 'file', path: 'fonts'})
		},
		accept: {
			type: String,
			default: '*/*'
		},
		uploadText: {
			type: String,
			default: '上传文件'
		},
		// 是否返回包含网址前缀的完整路径
		fullpath: {
		    type: Boolean,
		    default: true
		},
		disabled: {
		    type: Boolean,
		    default: false
		}
	},
	emits: ['update:modelValue'],
    setup(props, { emit }) {
        const modelValue = ref(props.modelValue);
        
        // 触发文件选择
        const triggerUpload = () => {
            const uploadInput = document.querySelector('input[type="file"]')
            if (uploadInput) uploadInput.click()
        }

        // 文件类型校验
        const beforeUpload = (file) => {
            const accept = props.accept;
            if (accept === '*/*') return true;
            const allowedTypes = accept.split(',').map(ext => ext.trim().replace('.', ''));
            const fileExt = file.name.split('.').pop().toLowerCase();
            if (!allowedTypes.includes(fileExt)) {
                ElMessage.error(`仅支持 ${allowedTypes.join(', ')} 格式文件`);
                return false
            }
            // 系统字体冲突检查
            const uploadFileName = extractFileName(file.name);
            const systemFontNames = Object.keys(systemFontMap).map(extractFileName);
            if (systemFontNames.includes(uploadFileName)) {
                ElMessage.error(`[${uploadFileName}] 是系统默认字体，禁止上传`);
                return false;
            }
            return true
        }

        // 处理上传成功
        const handleSuccess = (res) => {
            console.log(res);
            if (res.code === 0) {
                const fullUrl = res.data;
                const relativePath = new URL(fullUrl).pathname.replace(/^\//, '') // 得到 "uploads/fonts/microsoftyahei.ttc"
                modelValue.value = props.fullpath ? fullUrl : relativePath; //根据需要返回是否有前缀的值
                emit('update:modelValue', modelValue.value);
                ElMessage.success('上传成功')
            } else {
                ElMessage.error(res.message || '上传失败')
            }
        }

        // 处理上传失败
        const handleError = () => {
            ElMessage.error('上传失败，请重试')
        }

        // 删除文件
        const handleDelete = () => {
            const fileName = extractFileName(modelValue.value); // 正确提取文件名
            const systemFontNames = Object.keys(systemFontMap).map(extractFileName);
            if (systemFontNames.includes(fileName)) {
                return ElMessage.error('默认字体禁止删除')
            }
            ElMessageBox.confirm('确认删除该文件吗？', '警告', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                modelValue.value = ''
                emit('update:modelValue', '')
            }).catch((error) => {
                if (error === 'cancel') {
                    // ElMessage.info('已取消删除')
                } else {
                    console.error('删除操作异常:', error)
                    ElMessage.error('删除操作异常')
                }
            })
        }

        return {
            handleDelete,
            handleError,
            handleSuccess,
            beforeUpload,
            triggerUpload,
        }
        
    },
    
    template: `
        <div style="display: flex; align-items: center;">
            <!-- 已上传文件展示 -->
            <div v-if="modelValue" style="display: flex; align-items: center; gap: 8px; flex: 1;">
                <el-icon style="flex-shrink: 0;"><Document /></el-icon>
                <span style="flex: 1; overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width: 280px;">
                    {{ modelValue }}
                </span>
                <div style="display: flex; gap: 8px; flex-shrink: 0;">
                    <el-button type="danger" :disabled="disabled" size="small" style="margin: 0; padding: 5px 10px;" @click="handleDelete">删除</el-button>
                    <el-button type="primary" :disabled="disabled" size="small" style="margin: 0; padding: 5px 10px;" @click="triggerUpload">替换</el-button>
                </div>
            </div>
        
            <!-- 上传组件 -->
            <el-upload v-show="!modelValue" ref="uploadRef" :action="action" :data="data" :show-file-list="false" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :accept="accept"style="flex: 1;">
                <template #trigger>
                    <el-button type="primary" :disabled="disabled" style="display: inline-flex; align-items: center; padding: 8px 15px;">
                        <el-icon style="margin-right: 5px;"><Upload /></el-icon>
                        {{ uploadText }}
                    </el-button>
                </template>
            </el-upload>
        </div>
`
}